#include "MessageDigest.h"
#include "MD5.h"
#include "SHA1.h"
#include "SHA256.h"

const int MessageDigest::TYPE_UNKNOWN	= 0;
const int MessageDigest::TYPE_MD5		= 1;
const int MessageDigest::TYPE_SHA1		= 10;
const int MessageDigest::TYPE_SHA256	= 12;


MessageDigest::MessageDigest(int type) {
	switch (type)
	{
	case TYPE_MD5:
		mAlgorithm = new MD5();
		break;
	case TYPE_SHA1:
		mAlgorithm = new SHA1();
		break;
	case TYPE_SHA256:
		mAlgorithm = new SHA256();
		break;

	default:
		mAlgorithm = NULL;
		return;
		break;
	}

	mType = mAlgorithm->getType();
	mSize = mAlgorithm->getSize();
}

const unsigned char *MessageDigest::digest(const void *data, unsigned int size) {
	init();
	update(data, size);
	final();
	return getDigest();
}

void MessageDigest::digestHex(char *hex, const unsigned char *digest, unsigned int size) {
	static const char HEX[] = "0123456789abcdef";
	for(int i=0; i<size; ++i) {
		hex[i*2+0] = HEX[(digest[i]>>4)&0xF];
		hex[i*2+1] = HEX[(digest[i]>>0)&0xF];
	}
	hex[size*2] = '\0';
}

const std::string MessageDigest::digestHex(const unsigned char *digest, unsigned int size) {
	static const char HEX[] = "0123456789abcdef";
	std::string hex(size<<1, '0');
	for(int i=0; i<size; ++i) {
		hex[i*2+0] = HEX[(digest[i]>>4)&0xF];
		hex[i*2+1] = HEX[(digest[i]>>0)&0xF];
	}
	return hex;
}
